<!--
 * @Descripttion: (子篮信息/cks_basket)
 * @Author: (admin)
 * @Date: (2025-02-23)
-->
<template>
    <div>
        <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>

            <el-form-item label="盖板码" prop="coverCode">
                <el-input v-model="queryParams.coverCode" placeholder="" clearable style="width: 240px"/>
            </el-form-item>
            <el-form-item :label="$t('op30.col-1')" prop="bottomPlateCode">
                <el-input v-model="queryParams.bottomPlateCode" placeholder="" clearable style="width: 240px"/>
            </el-form-item>
            <el-form-item label="最大条数" prop="limit">
                <el-input-number v-model="queryParams.limit" :min="1" :max="100000" :controls="false" />
                <!-- <el-input v-model="queryParams.limit" placeholder="" clearable style="width: 120px"/> -->
            </el-form-item>
            <el-form-item :label="$t('op30.col-21')">
                <el-date-picker v-model="queryParams.dateRange" style="width: 360px"  
                type="datetimerange" :default-time="defaultTime2"  value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="-" start-placeholder="" end-placeholder=""></el-date-picker>
            </el-form-item>
            <el-form-item>
                <!-- <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button> -->
            </el-form-item>
        </el-form>
        <!-- 工具区域 -->
        <el-row :gutter="15" class="mb10">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['system:user:export']">
                    {{ $t('btn.export') }}
                </el-button>
            </el-col>
            <right-toolbar v-if="false" v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
       
        </el-row>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload name="file" ref="uploadRef" :limit="1" accept=".xlsx,.xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <!-- <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div> -->
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <el-button @click="upload.open = false">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitFileForm">{{ $t('btn.submit') }}</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup name="cks-export-index">
import {
    listCksBasket,
    addCksBasket, delCksBasket,
    updateCksBasket, getCksBasket,
}
    from '@/api/business/cksbasket.js'
import { getToken } from '@/utils/auth'
import { downFile } from '@/utils/request'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    sort: '',
    sortType: 'asc',
    limit:10000

})
const defaultTime2 = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
] // '12:00:00', '08:00:00'
const columns = ref([
    //{ visible: false, prop: 'id', label: 'Id' },
    { visible: true, prop: 'blueCode', label: '子篮码' },
    { visible: true, prop: 'type', label: '子篮类型' },
    { visible: true, prop: 'stock', label: '零件库存' },
    { visible: true, prop: 'updateTime', label: '最后更新时间' },
    //{ visible: false, prop: 'createdTime', label: '创建时间' },
    //{ visible: false, prop: 'isDeleted', label: 'IsDeleted' },
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]


function getList() {
    loading.value = true
    listCksBasket(queryParams).then(res => {
        const { code, data } = res
        if (code == 200) {
            dataList.value = data.result
            total.value = data.totalNum
            loading.value = false
        }
    })
}

// 查询
function handleQuery() {
    queryParams.pageNum = 1
    getList()
}

// 重置查询操作
function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
}
// 自定义排序
function sortChange(column) {
    var sort = undefined
    var sortType = undefined

    if (column.prop != null && column.order != null) {
        sort = column.prop
        sortType = column.order

    }
    queryParams.sort = sort
    queryParams.sortType = sortType
    handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
    single: true,
    multiple: true,
    form: {},
    rules: {
        createdTime: [{ required: true, message: "创建时间不能为空", trigger: "blur" }],
        isDeleted: [{ required: true, message: "IsDeleted不能为空", trigger: "blur" }],
    },
    options: {
        // 子篮类型 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
        typeOptions: [],
        statusOptions: [
            { dictLabel: '清洗线', dictValue: '1', langKey: "cleaningLineType.01" },
            { dictLabel: '缓存线', dictValue: '2', langKey: "cleaningLineType.02" }
        ]
    }
})

const { form, rules, options, single, multiple } = toRefs(state)

proxy.getDicts('cks_part_type').then((response) => {
    state.options.typeOptions = response.data
})

// 关闭dialog
function cancel() {
    open.value = false
    reset()
}

// 重置表单
function reset() {
    form.value = {
        id: null,
        blueCode: null,
        type: null,
        stock: null,
        updateTime: null,
        createdTime: null,
        isDeleted: null,
    };
    proxy.resetForm("formRef")
}


// 添加按钮操作
function handleAdd() {
    reset();
    open.value = true
    title.value = '添加子篮信息'
    opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
    reset()
    const id = row.id || ids.value
    getCksBasket(id).then((res) => {
        const { code, data } = res
        if (code == 200) {
            open.value = true
            title.value = '修改子篮信息'
            opertype.value = 2

            form.value = {
                ...data,
            }
        }
    })
}

// 添加&修改 表单提交
function submitForm() {
    proxy.$refs["formRef"].validate((valid) => {
        if (valid) {

            if (form.value.id != undefined && opertype.value === 2) {
                updateCksBasket(form.value).then((res) => {
                    proxy.$modal.msgSuccess("修改成功")
                    open.value = false
                    getList()
                })
            } else {
                addCksBasket(form.value).then((res) => {
                    proxy.$modal.msgSuccess("新增成功")
                    open.value = false
                    getList()
                })
            }
        }
    })
}

// 删除按钮操作
function handleDelete(row) {
    const Ids = row.id || ids.value

    proxy
        .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
            confirmButtonText: proxy.$t('common.ok'),
            cancelButtonText: proxy.$t('common.cancel'),
            type: "warning",
        })
        .then(function () {
            return delCksBasket(Ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess("删除成功")
        })
}





handleQuery()
/*** 导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/business/CksBasket/importData'
})
/** 导入按钮操作 */
function handleImport() {
    upload.title = '导入子篮数据'
    upload.open = true
}
/** 下载模板操作 */
function importTemplate() {
    proxy.download('/business/CksBasket/downloadTemplate', '子篮数据模板')
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    const { code, msg, data } = response
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].clearFiles()
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + '已更新' + '</div>', '导入结果', {
        dangerouslyUseHTMLString: true
    })
    getList()
}

/** 提交上传文件 */
function submitFileForm() {

    console.log('submitFileForm', proxy.$refs['uploadRef'])
    proxy.$refs['uploadRef'].submit()
}

/** 导出按钮操作 */
async function handleExport() {

    const { coverCode, bottomPlateCode, dateRange,limit } = queryParams
    const body = { coverCode, bottomPlateCode}
    proxy.addDateRange(body, dateRange) 
    // 判断 body 中的属性内容是否至少有 1 项不是空
    const hasValue = Object.values(body).some(value => value!== undefined && value!== null && String(value).trim()!== '')
    if(!hasValue)
    {
        proxy.$modal.msgError('请至少输入1个查询条件')
        return
    }
    if(limit<=0 || limit> 1000000)
    {
        proxy.$modal.msgError('最大条数输入有误')
        return
    }
    body.limit = limit
    console.log('body',body)
 
    await QueryExportData(body)

   

    // proxy.$modal
    //     .confirm('是否确认导出数据项?', '警告', {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning'
    //     })
    //     .then(async () => {
    //         await QueryExportData(queryParams)
    //     })
}


async function QueryExportData(query) {
    // return request({
    //   url: '/system/User/export',
    //   method: 'get',
    //   params: query
    // })
    await downFile('/business/CksExport/QueryExportData', { ...query })
}

</script>